<template>
  <el-dialog v-model="showDialog"
             :title="title"
             :width="width"
             :destroy-on-close="true"
             :show-close="false"
             :draggable="true"
             :close-on-click-modal="false">
    <template #title>
      <slot name="header">
        {{ title }}
      </slot>
    </template>
    <el-form :model="updatePasswordForm"
             ref="updatePasswordFormRef"
             :rules="updatePasswordFormRules"
             status-icon>
      <el-form-item prop="oldPassword">
        <el-input v-model="updatePasswordForm.oldPassword" placeholder="请输入旧密码" type="password" show-password>
          <template #prefix>
            <el-icon>
              <Unlock/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="updatePasswordForm.password" placeholder="请输入新密码" type="password" show-password>
          <template #prefix>
            <el-icon>
              <Unlock/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="checkPassword">
        <el-input v-model="updatePasswordForm.checkPassword" placeholder="请确认新密码" type="password" show-password>
          <template #prefix>
            <el-icon>
              <Unlock/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="showCancel" @click="cancel(updatePasswordFormRef)">{{ cancelText }}</el-button>
        <el-button type="primary" @click="confirm(updatePasswordFormRef)" :loading="updatePasswordForm.okLoading">{{ confirmText }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {reactive, ref, watch} from "vue";
import type {FormInstance, FormRules} from "element-plus";
import {Unlock} from "@element-plus/icons-vue"
import {userUpdatePasswordReq} from "@/api/login/login.ts";
import {elMessageTip, errorMessageTip} from "@/utils/tip-utils.ts";
import {RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import {getUserInfo} from "@/utils/user-utils.ts";

interface UpdatePasswordForm {
  oldPassword: string;
  password: string;
  checkPassword: string;
  okLoading: boolean;
}

const updatePasswordForm = reactive<UpdatePasswordForm>({
  oldPassword: '',
  password: '',
  checkPassword: '',
  okLoading: false
})

const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '弹窗'
  },
  width: {
    type: String,
    default: '30%'
  },
  showCancel: {
    type: Boolean,
    default: true
  },
  cancelText: {
    type: String,
    default: '取消'
  },
  confirmText: {
    type: String,
    default: '确定'
  }
})

const updatePasswordFormRef = ref<FormInstance>()

const updatePasswordFormRules = reactive<FormRules<UpdatePasswordForm>>({
  oldPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
  checkPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ]
})

const emit = defineEmits(['update:showDialog', 'confirm', 'cancel'])

// 内部维护的可见性状态（解决直接修改prop的问题）
let showDialog = ref(props.showDialog)

// 监听外部传入的modelValue变化
watch(() => props.showDialog, val => {
  showDialog.value = val
})

// 确认按钮点击
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      commonUpdatePassword(formEl)
    } else {
      errorMessageTip('请填写完整信息')
    }
  })
}

// 通用更新密码请求
const commonUpdatePassword = async (formEl: FormInstance | undefined) => {
  updatePasswordForm.okLoading = true
  const userInfo = getUserInfo();

  const params = {
    id: userInfo.userId,
    oldPassword: updatePasswordForm.oldPassword,
    password: updatePasswordForm.password,
    checkPassword: updatePasswordForm.checkPassword
  }
  const res: any = await userUpdatePasswordReq(params)
  updatePasswordForm.okLoading = false
  elMessageTip(res.tipType, res.message);
  if (res.code === RESPONSE_CODE_SUCCESS) {
    close(formEl)
  }
}

// 取消按钮点击
const cancel = (formEl: FormInstance | undefined) => {
  close(formEl)
}

// 关闭弹窗（不触发事件）
const close = (formEl: FormInstance | undefined) => {
  emit('update:showDialog', false)
  showDialog.value = false
  resetForm(formEl)
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style scoped>

</style>